﻿using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Replacing;

namespace WordStudy20250123.T001
{
    public class ImageReplaceCallback : IReplacingCallback
    {
        private readonly string _imagePath;
        private readonly double _width;
        private readonly double _height;

        public ImageReplaceCallback(string imagePath, double width = 80, double height = 80)
        {
            _imagePath = imagePath;
            _width = width;
            _height = height;
        }

        public ReplaceAction Replacing(ReplacingArgs args)
        {
            // 创建文档构建器
            DocumentBuilder builder = new DocumentBuilder(args.MatchNode.Document as Document);

            // 移动到匹配位置
            builder.MoveTo(args.MatchNode);

            try
            {
                // 插入图片
                Shape shape = builder.InsertImage(_imagePath);

                // 设置图片大小
                shape.Width = _width;
                shape.Height = _height;
                // 可选：设置图片对齐方式
                shape.WrapType = WrapType.Inline;

                // 返回替换成功
                return ReplaceAction.Replace;
            }
            catch (Exception)
            {
                // 如果插入失败，保留原文本
                return ReplaceAction.Skip;
            }
        }

    }
}